package com.atguigu.realtime.gmallpublisher.service;

import com.atguigu.realtime.gmallpublisher.mapper.OrderMapper;
import com.atguigu.realtime.gmallpublisher.util.DSLUtil;
import com.atguigu.realtime.gmallpublisher.util.MyEsUtil;
import io.searchbox.client.JestClient;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import io.searchbox.core.search.aggregation.TermsAggregation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author lzc
 * @Date 2020/11/14 10:07
 */
@Service
public class PublisherServiceImpl implements PublisherService {
    @Override
    public Long getDau(String date) throws IOException {
        /*
        从es去读数据
         */
        // 1. 获取es客户端
        JestClient client = MyEsUtil.getClient();
        // 2. 查询数据
        //2.1 封装查询数据
        Search search = new Search.Builder(DSLUtil.getDSL())
                .addIndex("gmall_dau_info_" + date)
                .addType("_doc")
                .build();
        SearchResult searchResult = client.execute(search);
        // 3. 解析
        Long total = searchResult.getTotal();
        client.shutdownClient();

        // 4. 返回最后的数据
        return total == null ? 0 : total;
    }

    @Override
    public Map<String, Long> getHourDau(String date) throws IOException {
        JestClient client = MyEsUtil.getClient();
        Search search = new Search.Builder(DSLUtil.getHourDSL())
                .addIndex("gmall_dau_info_" + date)
                .addType("_doc")
                .build();
        SearchResult searchResult = client.execute(search);

        // 解析聚合结果
        TermsAggregation groupByHourAgg = searchResult.getAggregations()
                .getTermsAggregation("group_by_hour");
        // 最终返回的结果
        HashMap<String, Long> result = new HashMap<>();
        if (groupByHourAgg != null) {
            for (TermsAggregation.Entry bucket : groupByHourAgg.getBuckets()) {
                String hour = bucket.getKey();
                Long count = bucket.getCount();
                result.put(hour, count);
            }
        }

        client.shutdownClient();
        return result;
    }

    @Autowired
    OrderMapper order;
    @Override
    public BigDecimal getOrderAmount(String date) {
        return order.getOrderAmount(date);
    }

    @Override
    public Map<String, BigDecimal> getHourOrderAmount(String date) {
        List<Map<String, Object>> hourOrderAmount = order.getHourOrderAmount(date);

        Map<String, BigDecimal> result = new HashMap<>();

        for (Map<String, Object> map : hourOrderAmount) {
            String hour = map.get("create_hour").toString();
            BigDecimal total = (BigDecimal) map.get("total");
            result.put(hour, total);
        }

        return  result;
    }
}
